var e = getApp();
var app = getApp();
// 在页面中定义激励视频广告
let videoAd = null

Page({
    data: {
        icons: {
            fans: "/resource/icon/invite/fans.png",
            more: "/resource/icon/invite/more.png"
        },
        emptyList: [ 1, 2, 3, 4, 5, 6 ],
        inviteList: [],
        userInfo: e.user,
        setting: {
            unit_id: "",
            per_video_gold: "",
            per_invite_gold: 0
        },
        showVideoAdButton: !1,
        rewardedVideoAd: null,
        shareScene: "invite"
    },
    onLoad: function(t) {
    // 在页面onLoad回调事件中创建激励视频广告实例
    let that = this;
    if (wx.createRewardedVideoAd) {
        videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-e571e1666e78867e'
        })
        videoAd.onLoad(() => {})
        videoAd.onError((err) => {})
        videoAd.onClose((res) => {
            // 用户点击了【关闭广告】按钮
            if (res && res.isEnded) {
                // 正常播放结束，可以下发游戏奖励
                that.update();
            } else {
                // 播放中途退出，不下发游戏奖励
            }
        })
    }
  
        this.onQuery();
        return;
        this.loadMyInviteList(), e.initConfig(this.initConfigBack);
    },
    update: function(){
        let that = this;

        const db = wx.cloud.database()

        let _id = app.globalData.openid;
        const _ = db.command
        db.collection('profiles').doc(_id).update({
            data: {
                // 表示指示数据库将字段自增 -100
                num: _.inc(500)
            }
        })
        .then(res=>{
            console.log(res)
            this.setData({
                num: this.data.num+500
            },()=>{
                wx.showToast({
                    title: '+500',
                    icon: 'success',
                    duration: 2000
                })
                  
            })
        })
        .catch(err=>{
            console.log(err);
        })
    },
    onQuery: function(){
        let emptyList = this.data.emptyList;
        const db = wx.cloud.database()
        db.collection('invites')
        .where({
            status: 1
        })
        .orderBy('time', 'desc')
        .limit(6)
        .get().then(res => {
            console.log('[数据库] [查询记录] 成功: ', res)
            wx.hideLoading()
            let arr = res.data;
            let invites = [];
            arr.forEach((element,index) => {
                element.index = index;
                invites.push(element);
                emptyList.pop();
            });
            this.setData({
                invites,
                emptyList
            });
        })
        
    },
    loadMyInviteList: function() {
        var t = this;
        e.util.request({
            url: "entry/wxapp/myinvite",
            showLoading: !1,
            success: function(e) {
                var i = e.data.data.list, n = t.data.emptyList;
                i.length > 0 && n.splice(0, i.length), t.setData({
                    inviteList: i,
                    emptyList: n
                });
            },
            fail: function(e) {
                console.log("check fail");
            }
        });
    },
    onReady: function() {},
    initConfigBack: function() {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : null, t = this;
        if (null != e) {
            var i = e.setting;
            i.status && t.setData({
                setting: i.data
            }), t.initRewardVideoAd();
        }
    },
    initRewardVideoAd: function() {
        if (!1 !== e.canIUseRewardedVideoAd) {
            var t = this, i = t.data.setting;
            if (0 !== parseInt(i.video_ad_status) && "" != i.video_unit_id) {
                var n = null;
                wx.createRewardedVideoAd && ((n = wx.createRewardedVideoAd({
                    adUnitId: i.video_unit_id
                })).onLoad(function() {
                    t.setData({
                        showVideoAdButton: !0
                    });
                }), n.onError(function(e) {
                    console.log(e), t.setData({
                        showVideoAdButton: !1
                    });
                }), n.onClose(function(e) {
                    e && e.isEnded && t.sendVideoReward();
                })), t.setData({
                    rewardedVideoAd: n
                });
            }
        }
    },
    code: "",
    sendVideoReward: function() {
        var t = this;
        e.util.request({
            url: "entry/wxapp/sendReward",
            data: {
                v: e.av,
                code: t.code
            },
            showLoading: !1,
            success: function(i) {
                0 === i.data.code ? (t.setData({
                    showVideoAdButton: i.data.data.show_video
                }), e.updateUserGold(t.data.setting.per_video_gold, "+", t.onShow), e.happy("金币 + " + t.data.setting.per_video_gold), 
                setTimeout(function() {
                    i.data.data.show_video || (e.updateConfig = !0);
                }, 500)) : e.sad(i.data.message);
            },
            fail: function(e) {
                console.log("check fail");
            }
        });
    },
    showRewardVideoAd: function() {
       // 用户触发广告后，显示激励视频广告
        if (videoAd) {
            videoAd.show().catch(() => {
            // 失败重试
            videoAd.load()
                .then(() => videoAd.show())
                .catch(err => {
                console.log('激励视频 广告显示失败')
                })
            })
        }
    },
    onShow: function() {

        console.log("invite show")
        this.onGetUUID();
        this.setData({
            num: app.globalData.num
        })
        return;
        this.setData({
            userInfo: e.user
        });
    },
    onShareAppMessage: function() {
        var t = e.getShareByScene(this.data.shareScene), i = this.data.userInfo, n = "?from=" + this.data.shareScene;
        return "1" == i.status && (n += "&vid=" + i.id), {
            title: t.title,
            path: e.pages.index + '?openid='+app.globalData.openid+'&uuid='+this.data.uuid,
            imageUrl: t.imageUrl,
            success: function(e) {},
            fail: function(e) {},
            complete: function() {}
        };
    },
    onGetUUID: function() {
        let that = this;
        // 调用云函数
        wx.cloud.callFunction({
          name: 'getUUID',
          data: {}
        })
        .then(res=>{
          console.log('[云函数] [getUUID]: ', res)
          that.setData({
            uuid: res.result.uuid
          })
        })
        .catch(err=>{
          console.error('[云函数] [getUUID] 调用失败', err)
          wx.navigateTo({
            url: '../deployFunctions/deployFunctions',
          })
        })
      }
});